package com.suriya.thirukural;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MainActivity extends Activity
{
    private ThirukuralContext _context;
    private ListView          _menu;
    AssetManager              assetManager;
    int                       depth   = 0;
    int[]                     section = null;
    private int               orientation;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        _context = (ThirukuralContext) getApplication();
        _context.init();

        getWindow().setFormat(PixelFormat.RGBA_8888);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
        
        assetManager = getAssets();
        Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        orientation = display.getOrientation();

        Intent intent = getIntent();

        section = intent.getIntArrayExtra("section");
        if(section == null) section = new int[0];
        depth = intent.getIntExtra("depth", 0);

        Log.d("Suriya", "Depth:" + depth);

        setContentView(R.layout.main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.screenview);
        layout.setBackgroundDrawable(_context.getBackgroundImage());

        _menu = (ListView) findViewById(android.R.id.list);

        String sectionStr = "sections";
        String expName = "section_";

        for(int currSection : section)
        {
            sectionStr += ("/" + currSection);
            expName += ("" + currSection + "_");
        }

        {
            String imgPath = "sections/";
            String filenamePart = "section";

            for(int idx = 1; idx <= depth && idx <= 3; idx++)
            {
                filenamePart += "_" + section[idx - 1];
                ImageView img = null;
                if(idx == 1)
                {
                    img = (ImageView) findViewById(R.id.imgsec1);
                    img.setOnClickListener(sectionHeadClickListener);
                }
                else if(idx == 2)
                {
                    img = (ImageView) findViewById(R.id.imgsec2);
                    img.setOnClickListener(sectionHeadClickListener);
                }
                else if(idx == 3)
                {
                    img = (ImageView) findViewById(R.id.imgsec3);
                    img.setOnClickListener(sectionHeadClickListener);
                }

                Log.d("Suriya", "Loading image:" + imgPath + filenamePart + ".png");
                if(img != null) img.setImageBitmap(getBitmap(assetManager, this, imgPath + filenamePart + ".png"));

                imgPath += "" + section[idx - 1] + "/";

            }
        }

        if(depth < 3)
        {
            LinkedList<String> list = new LinkedList<String>();

            try
            {
                Log.d("Suriya", "SectionStr:" + sectionStr);
                Set<String> availableSections = new TreeSet<String>();

                for(String curr : assetManager.list(sectionStr))
                {
                    if(curr.startsWith("section_"))
                    {
                        availableSections.add(curr);
                    }
                }

                int idx = 0;
                while(true)
                {
                    idx++;

                    String filename = expName + idx + ".png";
                    if(availableSections.contains(filename))
                    {
                        list.add(sectionStr + "/" + filename);
                        continue;
                    }
                    break;
                }

            }
            catch(IOException e)
            {
            }

            String[] items = list.toArray(new String[] {});
            _menu.setAdapter(new SectionArrayAdapter(_context, items));
        }
        else if(depth == 3)
        {
            String kural = sectionStr + "/kural.png";
            Log.d("Suriya", "Showing:" + kural);
            String[] items = new String[] { "", "", "", "", "", "", "", "", "", "" };
            _menu.setAdapter(new KuralArrayAdapter(_context, kural, items));
        }
    }

    public void onGotoMainMenu(View v)
    {
        if(depth == 0) return;
        
        Intent intent = new Intent(_context, MainActivity.class);
        startActivity(intent);
    }
    
    public static Bitmap getBitmap(AssetManager assetManager, Context context, String filename)
    {
        try
        {
            InputStream stream = assetManager.open(filename);
            BufferedInputStream bis = new BufferedInputStream(stream);
            Bitmap ret = BitmapFactory.decodeStream(bis);

            int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 25.0,
                                                         context.getResources().getDisplayMetrics());
            int width = ret.getWidth() * height / ret.getHeight();
            ret = Bitmap.createScaledBitmap(ret, width, height, true);
            bis.close();
            stream.close();
            return ret;
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    class KuralArrayAdapter extends ArrayAdapter<String>
    {
        private LayoutInflater mInflater;
        Bitmap                 kuralBm = null;

        public KuralArrayAdapter(Context context, String kural, String[] items)
        {
            super(context, R.layout.kural_item, items);
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            try
            {
                InputStream stream = assetManager.open(kural);
                BufferedInputStream bis = new BufferedInputStream(stream);
                kuralBm = BitmapFactory.decodeStream(bis);
                bis.close();
                stream.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if(convertView == null)
            {
                view = mInflater.inflate(R.layout.kural_item, parent, false);
            }
            else
            {
                view = convertView;
            }

            LayoutParams param = view.getLayoutParams();

            if(orientation == 1)
            {
                param.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 80.0,
                                                               getResources().getDisplayMetrics());
            }
            else
            {
                param.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 50.0,
                                                               getResources().getDisplayMetrics());
            }
            view.setLayoutParams(param);

            ImageView img = (ImageView) view.findViewById(R.id.image);

            view.setTag("" + (position + 1));

            if(kuralBm != null)
            {
                Bitmap bm = Bitmap.createBitmap(kuralBm, 0, position * (kuralBm.getHeight() / 10), kuralBm.getWidth(),
                                                kuralBm.getHeight() / 10);
                img.setImageBitmap(bm);
            }

            view.setOnClickListener(kuralListClickListener);
            return view;
        }
    }

    private OnClickListener kuralListClickListener = new OnClickListener() {

                                                       @Override
                                                       public void onClick(View v)
                                                       {
                                                           int position = Integer.parseInt((String) v.getTag());

                                                           Intent intent = new Intent(_context, KuralView.class);
                                                           intent.putExtra("section", section);
                                                           intent.putExtra("depth", depth + 1);
                                                           intent.putExtra("kuralNum", position);
                                                           startActivity(intent);
                                                       }
                                                   };

    class SectionArrayAdapter extends ArrayAdapter<String>
    {
        private LayoutInflater mInflater;

        public SectionArrayAdapter(Context context, String[] items)
        {
            super(context, R.layout.section_item, items);
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if(convertView == null)
            {
                view = mInflater.inflate(R.layout.section_item, parent, false);
            }
            else
            {
                view = convertView;
            }

            ImageView img = (ImageView) view.findViewById(R.id.image);
            String item = getItem(position);

            view.setTag(item);
            try
            {
                InputStream stream = assetManager.open(item);
                BufferedInputStream bis = new BufferedInputStream(stream);
                Bitmap bm = BitmapFactory.decodeStream(bis);
                bis.close();
                stream.close();
                img.setImageBitmap(bm);
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }

            view.setOnClickListener(sectionClickListener);
            return view;
        }
    }

    public OnClickListener sectionClickListener     = new OnClickListener() {

                                                         @Override
                                                         public void onClick(View v)
                                                         {
                                                             String item = (String) v.getTag();

                                                             item = item.substring(item.indexOf("section_") + 8);
                                                             item = item.replace(".png", "");
                                                             String[] sections = item.split("_");
                                                             int newSections[] = new int[sections.length];
                                                             for(int idx = 0; idx < sections.length; idx++)
                                                             {
                                                                 newSections[idx] = Integer.parseInt(sections[idx]);
                                                             }
                                                             Intent intent = new Intent(_context, MainActivity.class);
                                                             intent.putExtra("section", newSections);
                                                             intent.putExtra("depth", depth + 1);
                                                             startActivity(intent);
                                                         }
                                                     };

    private OnClickListener sectionHeadClickListener = new OnClickListener() {

                                                         @Override
                                                         public void onClick(View v)
                                                         {
                                                             int newSections[] = {};

                                                             if(v == findViewById(R.id.imgsec1))
                                                             {
                                                                 newSections = new int[1];
                                                             }
                                                             else if(v == findViewById(R.id.imgsec2))
                                                             {
                                                                 newSections = new int[2];
                                                             }
                                                             else if(v == findViewById(R.id.imgsec3))
                                                             {
                                                                 newSections = new int[3];
                                                             }
                                                             
                                                             if(depth == newSections.length) return;

                                                             for(int idx = 0; idx < newSections.length; idx++)
                                                             {
                                                                 newSections[idx] = section[idx];
                                                             }

                                                             Intent intent = new Intent(_context, MainActivity.class);
                                                             intent.putExtra("section", newSections);
                                                             intent.putExtra("depth", newSections.length);
                                                             startActivity(intent);
                                                         }
                                                     };
}